package rabbitmq.simply;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class CustomDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 设置基本配置
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setHost("8.152.203.113");
        factory.setPort(5672);
        factory.setVirtualHost("bite");

        // 创立链接
        Connection connection = factory.newConnection();
        // 创建 channel
        Channel channel = connection.createChannel();
        // 声明队列（可以省略 但要保证里面必须有对应的队列 所以一般不省略）
        channel.queueDeclare("hello", true, false, true, null);
        // 消费
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback) 
         * queue：目标队列
         * autoAck：是否自动通知rabbitMQ(通知后queue会自动删除)
         * callback 回调函数 执行一系列逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             *
             * @param consumerTag 标签
             * @param envelope 像交换机、路由等信息
             * @param properties 配置信息
             * @param body 存储的消息
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("收到消息：" + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);
        Thread.sleep(2000);
        channel.close();
        connection.close();
    }
}
